import axios from 'axios'
import store from '@/store/store.js';
import router from '@/router/router';
import AppConstants from '@/constants/AppConstants.js';

let net = {
    title: null,
    baseUrl: null,
    req: null,
};

net.title = function (title) {
    title = title ? title + '|管理端': '丰宁麻将后台';
    window.document.title = title;
}

// 读取系统环境变量
const baseUrl = process.env.NODE_ENV === 'production' ? AppConstants.serverApi:  '/api';

net.baseUrl = baseUrl;

net.req = axios.create({
    baseURL: baseUrl,
    timeout: 30000
});

// http request 拦截器
net.req.interceptors.request.use(
    config => {
        if(store.getters.token){
            // 判断是否存在token，如果存在的话，则每个http header都加上token
            config.headers.token = `${store.getters.token}`;
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

// http response 拦截器
net.req.interceptors.response.use(
    response => {
        if (response.data.rescode == 102 && router.currentRoute.name != 'login') {
            // 返回102会话过期代码-清除token信息并跳转到登录页面
            store.commit('loginOut');
            let rpath = router.currentRoute.fullPath;
            //登录页面，并重定向到发生会话失效的页面
            router.replace({
                path: '/login',
                query: { redirect: rpath }
            });
        }
        return response;
    },
    error => {
        if (error.response) {
            let rpath = router.currentRoute.fullPath;
            switch (error.response.status) {
                case 401:
                    // 返回 401 清除token信息并跳转到登录页面
                    store.commit('loginOut');
                    router.replace({
                        path: '/login',
                        query: { redirect: rpath }
                    })
                    break;
            }
        }
        // 返回接口返回的错误信息
        return Promise.reject(error.response.data)
    }
);

export default net;
